import pandas as pd
data = pd.read_csv("C:\\pythonProject\\test.csv")  # 替换为实际的文件路径
X = data.drop(columns=['risk_score', 'user_id', 'date'])  # 特征
y = data['risk_score']  # 目标变量
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
import shap

# 创建 SHAP 解释器
explainer = shap.TreeExplainer(rf_model)
shap_values = explainer.shap_values(X_test)

# SHAP Summary Plot
shap.summary_plot(shap_values, X_test, plot_type='bar')

# SHAP Dependence Plot（以 BMI 为例）
shap.dependence_plot("BMI", shap_values, X_test)

# 单个样本分析（解释第一个样本的预测结果）
sample = X_test.iloc[0]
shap.force_plot(explainer.expected_value, shap_values[0], sample, matplotlib=True)
